package com.example.play.view

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.GsonUtils
import com.example.base.app.RouterPath
import com.example.common.entity.CommendEntity
import com.example.common.mvi.BaseMviFragment
import com.example.play.R
import com.example.play.adapter.VideoCommentListAdapter
import com.example.play.databinding.FragmentCommentBinding
import com.example.play.intent.PlayViewIntent
import com.example.play.state.PlayUiState
import com.example.play.vm.PlayViewModel
import dagger.hilt.android.AndroidEntryPoint

@Route(path = RouterPath.PATH_FRAGMENT_DETAIL_COMMEND)
@AndroidEntryPoint
class CommentFragment : BaseMviFragment<FragmentCommentBinding>() {
    @Autowired
    @JvmField var itemId: String = ""

    @Autowired
    @JvmField var moduleType: Int = 0
    private val mViewModel: PlayViewModel by activityViewModels()

    private var commendList = mutableListOf<CommendEntity>()
    private lateinit var mCommendListAdapter: VideoCommentListAdapter

    override fun getLayoutId(): Int = R.layout.fragment_comment


    override fun initViews() {
        ARouter.getInstance().inject(this)

        mCommendListAdapter = VideoCommentListAdapter(commendList)

        mDataBinding.expandList.setAdapter(mCommendListAdapter)
    }

    override suspend fun sendViewIntent() {
        when (moduleType) {
            0 -> mViewModel.channel.send(PlayViewIntent.LoadCommentByUserId(0, itemId))
            1 -> mViewModel.channel.send(PlayViewIntent.LoadCommentByUserId(1, itemId))
        }
    }

    override suspend fun collectUIState() {
        mViewModel.uiSharedFlow.collect {
            when (it) {
                is PlayUiState.LoadVideoCommentSuccess -> updateVideoCommentList(
                    it.list
                )

                is PlayUiState.LoadVideoCommentFail -> showToastMsg(it.errorMsg)
                else -> {}
            }
        }
    }

    private fun updateVideoCommentList(list: List<CommendEntity>) {
        Log.i("=============", "updateVideoCommentList: " + GsonUtils.toJson(list))
        commendList.clear()
        commendList.addAll(list)
        mCommendListAdapter.notifyDataSetChanged()
    }


}